<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
    <meta>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>知云——针对编程的个性化学习推荐系统</title>
    <%
        pageContext.setAttribute("APP_PATH", request.getContextPath());
    %>
    <base href="${APP_PATH}">
    <link rel="shortcut icon" type="image/x-icon" href="${APP_PATH}/static/favicon.ico"/>
    <link rel="stylesheet" href="${APP_PATH}/static/css/bootstrap.min.css">
    <link rel="stylesheet" href="${APP_PATH}/static/css/toastr.min.css">
    <link rel="stylesheet" href="${APP_PATH}/static/css/offcanvas.css">
    <link rel="stylesheet" href="${APP_PATH}/static/css/fontawesome.min.css">


    <link rel="stylesheet" href="${APP_PATH}/static/css/pell.min.css">
    <link rel="stylesheet" href="${APP_PATH}/static/css/input-image-upload.css">


    <style>
        div[contenteditable='true'] img {
            width: 100%;
            overflow: hidden;
        }

        #questionArea img {
            width: 100%;
            overflow: hidden;
        }

        .previewAnswerArea img {
            width: 100%;
            overflow: hidden;
        }
    </style>

</head>
<body>
<jsp:include page="${APP_PATH}/common/head-question.jsp"/>
<div id="defaultDiv" data-userId="${user.id}" data-nickname="${user.nickname}" class="mt-2 col-sm-12 col-md-12 col-lg-9"
     style="margin-left: auto;margin-right: auto;">
    <div>
        <%--问题区域--%>
        <div data-questionId="${question.id}" data-questionUserId="${question.userid}" id="questionArea"
             class="p-3 rounded shadow-sm bg-white">
            <div class="border-bottom border-gray" style="position:relative;">
                <a id="btn-question-content" data-show="false" class="btn btn-sm btn-outline-info"
                   style="position: absolute;top:4px;right:4px;">显示问题详情</a>
                <h5>${question.questiontitle}</h5>
                <span style="font-size: small"><fmt:formatDate value="${question.edittime}" type="both"/></span>
            </div>
            <div id="questionContentArea" style="display: none;">
                <div style="height: 300px;overflow-y: scroll;">${question.questioncontent}</div>
            </div>
        </div>

        <%--按钮区域--%>
        <div id="buttonArea" class="d-flex my-2 p-3 rounded shadow-sm bg-white">
            <div class="flex-fill text-center"><a id="btn-answer-add" href="javascript:void(0);" class="text-dark"><i
                    class="fa fa-pen"></i>添加回答</a></div>
            <div class="flex-fill text-center"><a id="btn-question-star" href="javascript:void(0);" class="text-dark"><i
                    class="fa fa-star"></i>关注问题</a></div>
            <div class="flex-fill text-center"><a id="btn-answer-invite" href="javascript:void(0);" class="text-dark"><i
                    class="fa fa-user-friends"></i>邀请回答</a></div>
            <div class="flex-fill text-center"><a id="btn-question-report" href="javascript:void(0);" class="text-dark"><i
                    class="fa fa-arrow-circle-right"></i>举报问题</a></div>
        </div>

        <%--邀请回答区域--%>
        <div id="inviteArea" class="my-3 p-3 bg-white rounded shadow-sm" style="display: none;">
            <div id="inviteBodyArea">

            </div>
            <div id="invitePageNavArea">

            </div>
            <div>
                <a id="btn-invite-hide-btn" class="btn btn-sm btn-outline-info">收起</a>
            </div>
        </div>

        <%--添加回答区域--%>
        <div id="answerAddArea" class="my-2 p-3 rounded shadow-sm bg-white" style="display: none;">
            <%--内容--%>
            <form id="addAnswerForm">
                <div id="editor" class="pell"></div>
                <input type="hidden" id="answercontent" name="answerContent">
                <input type="hidden" name="questionId" value="${question.id}">
                <input type="hidden" name="userId" value="${user.id}">
                <div id="html-output" style="display: none"></div>
            </form>
            <div class="d-inline">
                <a id="btn-answer-submit" class="btn btn-sm btn-outline-danger">提交</a>
                <a id="btn-answer-add-cancel" class="btn btn-sm btn-outline-info ml-2">取消</a>
            </div>
        </div>

        <c:if test="${not empty answer}">
            <div id="targetAnswer" data-answerId="${answer.id}" class="my-2 p-3 rounded shadow-sm bg-white">
                    <%--头部信息--%>
                <div class="border-bottom border-dark pb-1">
                    <div>
                        <img src="${answer.user.headimgurl}" width="40px" height="40px" class="rounded-circle">
                        <a class="text-dark font-weight-bold" href="#">${answer.user.nickname}</a>
                    </div>
                    <div style="font-size: small">
                            ${answer.user.slogan}
                    </div>
                </div>
                    <%--回答内容--%>
                <div class="previewAnswerArea p-2">
                        ${answer.answercontent}
                </div>

                <div class="border-bottom border-gray pb-1" style="position: relative;">
                    <span><i class="fa fa-arrow-circle-up text-success"></i>${answer.upvotenum}</span>
                    <span class="ml-3"><i class="fa fa-arrow-circle-down text-danger"></i>${answer.downvotenum}</span>
                    <span class="ml-3 small">编辑于：<fmt:formatDate value="${answer.edittime}" type="date"/></span>
                        <%--选项按钮--%>
                    <div style="position: absolute;bottom:3px;right:3px;">
                        <a class="btn btn-sm btn-outline-secondary" data-flag="true" data-answerId="${answer.id}"
                           onclick="optionClick(this)"><i class='fa fa-angle-double-down'></i>选项</a>
                        <a data-answerid="${answer.id}" data-fromuserid="${answer.user.id}"
                           data-fromusername="${answer.user.nickname}"  onclick="addComment(this)"
                           class="ml-2 btn btn-sm btn-outline-secondary"><i class="fa fa-comments"></i>评论</a>
                    </div>
                </div>
                    <%--底部按钮--%>
                <div data-option-answerId="${answer.id}" style="display: none;">
                    <div class="d-flex p-2">
                        <div class="flex-fill text-center">
                            <a data-answerid="${answer.id}" href="javascript:void(0);" onclick="agreeAnswer(this)" class="text-dark"><i
                                    class="fa fa-arrow-circle-up text-success"></i>赞同回答</a></div>
                        <div class="flex-fill text-center">
                            <a data-answerid="${answer.id}" href="javascript:void(0);" onclick="disagreeAnswer(this)" class="text-dark"><i
                                    class="fa fa-arrow-circle-down text-danger"></i>反对回答</a></div>
                        <div class="flex-fill text-center">
                            <a data-answerid="${answer.id}" href="javascript:void(0);" onclick="viewComment(this)" class="text-dark"><i
                                    class="fa fa-comments"></i>查看评论</a></div>
                        <div class="flex-fill text-center">
                            <a data-answerid="${answer.id}" href="javascript:void(0);" onclick="reportAnswer(this)" class="text-dark"><i
                                    class="fa fa-arrow-circle-right"></i>举报回答</a></div>

                        <%--限定操作：当前登录用户是问题的提问者--%>
                        <c:if test="${user.id==question.userid}">
                            <div class="flex-fill text-center">
                                <a data-answerid="${answer.id}" href="javascript:void(0);" onclick="setTopAnswer(this)" class="text-dark"><i
                                        class="fa fa-arrow-circle-up text-info"></i>回答置顶</a>
                            </div>
                        </c:if>

                    </div>
                </div>

                    <%--评论区--%>
                <div class="bg-light border-top border-dark" data-answer-comment-area-answerid="${answer.id}">
                    <div data-answer-comment-answerid="${answer.id}"></div>
                    <div data-answer-comment-pagenav-answerid="${answer.id}"></div>
                </div>
            </div>
        </c:if>

        <%--回答区域--%>
        <div id="mainArea">
            <div id="answerArea">

            </div>

            <div id="pageNavArea">

            </div>
        </div>
    </div>
</div>


<%--图片上传弹出层--%>
<div id="imageUploadDiv"
     class="bg-light rounded border border-danger border-1 shadow-lg p-3"
     style="display: none;z-index: 99;top: 15%;left: 0;right: 0;width: 200px;margin-left:auto;margin-right:auto;position: fixed;">
    <form>
        <div class="form-group">
            <label for="uploaderInput">请选择你要上传的图片:</label>
            <div style="clear: both"></div>
            <div class="input-image-uploader">
                <ul class="input-image-files pl-0" id="uploaderFiles">

                </ul>
                <div class="input-image-box">
                    <input id="uploaderInput" class="input-image" type="file" name="files" accept="image/*">
                </div>
            </div>
            <div style="clear: both"></div>
        </div>
        <div>
            <span id="imgDivInfo">点击图片预览或修改</span>
        </div>
    </form>
    <a id="btn-submit" class="btn btn-sm btn-outline-info disabled">上传</a>
    <a id="btn-cancel" class="btn btn-sm btn-light">取消</a>
</div>

<%--图片预览层--%>
<div class="my-gallery" id="gallery">
    <span class="my-gallery-img" id="galleryImg"></span>
    <div class="my-gallery-option">
        <a href="javascript:void(0);" class="my-gallery-option-icon pt-2 pb-1">
            <i id="icon-delete" class="fa fa-trash-alt fa-2x" style="color: white"></i>
        </a>
    </div>
</div>

<%--图片预览层2--%>
<div class="my-gallery" id="gallery2">
    <span class="my-gallery-img" id="galleryImg2"></span>
</div>

<div>
    <a href="#"><img alt="置顶图标" src="/images/top.svg" width="30px" height="30px" style="position:fixed;z-index: 99999;right:20px;bottom: 20px;"></a>
</div>


<script src="${APP_PATH}/static/js/jquery-3.3.1.min.js"></script>
<script src="${APP_PATH}/static/js/bootstrap.min.js"></script>
<script src="${APP_PATH}/static/js/toastr.min.js"></script>
<script src="${APP_PATH}/static/js/offcanvas.js"></script>
<script src="${APP_PATH}/static/js/pell.min.js"></script>

<script>
    //判断是否登录
    function hasLogin() {
        var userId = $("#defaultDiv").attr("data-userId");
        if (userId.length === 16) {
            return true;
        } else {
            return false;
        }
    }

    function optionClick(ele) {
        if (!hasLogin()) {
            toastr.error("请先登录！");
            return false;
        }
        var flag = $(ele).attr("data-flag");
        var answerId = $(ele).attr("data-answerId");
        if (flag === "true") {
            $(ele).html("<i class='fa fa-angle-double-up'></i>收起");
            $(ele).attr("data-flag", false);
            $("div[data-option-answerId=" + answerId + "]").show();
        } else {
            $(ele).html("<i class='fa fa-angle-double-down'></i>选项");
            $(ele).attr("data-flag", true);
            $("div[data-option-answerId=" + answerId + "]").hide();
        }
    }

    //用户赞同回答
    function agreeAnswer(ele) {
        if (!hasLogin()) {
            toastr.error("请先登录！");
            return false;
        }
        var answerId = $(ele).attr("data-answerId");
        $.ajax({
            url: '/upvoteAnswer',
            data: {answerId: answerId},
            type: 'POST',
            success: function (result) {
                if (result.code === 100) {
                    toastr.success("操作成功！");
                } else {
                    toastr.error(result.extend.error);
                }
            }
        });
    }

    //用户反对回答
    function disagreeAnswer(ele) {
        if (!hasLogin()) {
            toastr.error("请先登录！");
            return false;
        }
        var answerId = $(ele).attr("data-answerId");
        $.ajax({
            url: '/downvoteAnswer',
            data: {answerId: answerId},
            type: 'POST',
            success: function (result) {
                if (result.code === 100) {
                    toastr.success("操作成功！");
                } else {
                    toastr.error(result.extend.error);
                }
            }
        });
    }

    //构建回答评论数据
    function buildpage_answercomment_mainarea(result, answerId) {
        //清空div data-answer-comment-answerid
        var $div_commentArea = $("div[data-answer-comment-answerid='" + answerId + "']");
        $div_commentArea.empty();
        $.each(result.extend.comments, function (index, item) {
            var fromuserid = item.fromuserid;
            var fromusername = item.fromusername;
            var touserid = item.touserid;
            var tousername = item.tousername;
            var message = item.comment;

            $div_commentArea.append($("<div> <a href='${APP_PATH}/user/"+fromuserid+"' class='text-success'>" + fromusername + "</a>@<a href='${APP_PATH}/user/"+touserid+"' class='text-secondary'>" + tousername + "</a>:<span  data-answerId='" + answerId + "' data-fromuserid='" + fromuserid + "' data-fromusername='" + fromusername + "' data-touserid='" + touserid + "' data-tousername='" + tousername + "' onclick='addComment(this)'>" + message + "</span></div>"));
        });
    }

    //添加评论
    function addComment(ele) {
        //弹框获取评论内容
        var answerid = $(ele).attr("data-answerId");
        var fromuserid = $(ele).attr("data-fromuserid");
        var fromusername = $(ele).attr("data-fromusername");
        var message = prompt("请输入回复内容：@"+fromusername);
        //获取登陆用户id和nickname
        var loginuserid = $("#defaultDiv").attr("data-userId");
        var loginusernickname = $("#defaultDiv").attr("data-nickname");
        if (message) {
            $.ajax({
                url: '/submit/answer/comment',
                data: {
                    message: message,
                    answerid: answerid,
                    fromuserid: loginuserid,
                    fromusername: loginusernickname,
                    touserid: fromuserid,
                    tousername: fromusername
                },
                type: 'POST',
                success: function (result) {
                    if (result.code === 100) {
                        //添加到页面中
                        $("div[data-answer-comment-answerid=" + answerid + "]").append($("<div><a href='${APP_PATH}/user/"+loginuserid+"' class='text-success'>" + loginusernickname + "</a>@<a href='${APP_PATH}/user/"+fromuserid+"' class='text-secondary'>" + fromusername + "</a>:" + message + "</div>"));
                    }
                }
            });
        }
    }

    //获取指定回答的指定页面评论数据
    function topage_answercomment(answerId) {
        $.ajax({
            url: '/answer/comment/' + answerId ,
            type: 'GET',
            success: function (result) {
                if (result.code === 100) {
                    if (result.extend.comments.length > 0) {
                        buildpage_answercomment_mainarea(result, answerId);
                    } else {
                        toastr.info("暂无任何评论,快来抢沙发！Σ(っ °Д °;)っ！！");
                    }
                } else {
                    toastr.error("获取评论失败");
                }
            }
        });
    }

    //查看评论
    function viewComment(ele) {
        var answerId = $(ele).attr("data-answerId");
        if (!hasLogin()) {
            toastr.error("请先登录！");
            return false;
        }
        //获取第一页评论数据
        topage_answercomment(answerId);
    }

    //举报回答
    function reportAnswer(ele) {
        if (!hasLogin()) {
            toastr.error("请先登录！");
            return false;
        }
        var answerId = $(ele).attr("data-answerId");
        $.ajax({
            url: '/report/answer/' + answerId,
            type: 'GET',
            success: function (result) {
                if (result.code === 100) {
                    toastr.success("操作成功！");
                } else {
                    toastr.error(result.extend.error);
                }
            }
        });
    }

    //置顶回答，仅限于问题提问者
    function setTopAnswer(ele) {
        if (!hasLogin()) {
            toastr.error("请先登录！");
            return false;
        }
        var answerId = $(ele).attr("data-answerId");
        //获取questionid
        var questionId = $("#questionArea").attr("data-questionId");
        $.ajax({
            url: '/setTop/answer/' + answerId,
            type: 'GET',
            success: function (result) {
                if (result.code === 100) {
                    window.location.href='/question/'+questionId;
                } else {
                    toastr.error(result.extend.error);
                }
            }
        });
    }

    //取消置顶回答，仅限于问题提问者
    function cancelSetTopAnswer(ele) {
        if (!hasLogin()) {
            toastr.error("请先登录！");
            return false;
        }
        var answerId = $(ele).attr("data-answerId");
        $.ajax({
            url: '/cancelSetTop/answer/' + answerId,
            type: 'GET',
            success: function (result) {
                if (result.code === 100) {
                    window.location.reload(true);
                } else {
                    toastr.error(result.extend.error);
                }
            }
        });
    }

    //删除回答，仅限于问题提问者
    function deleteAnswer(ele) {
        if (!hasLogin()) {
            toastr.error("请先登录！");
            return false;
        }
        var answerId = $(ele).attr("data-answerId");
        if (confirm("确定删除该回答吗？此操作不可逆，请确认！！！")) {
            $.ajax({
                url: '/delete/answer/' + answerId,
                type: 'GET',
                success: function (result) {
                    if (result.code === 100) {
                        window.location.reload(true);
                    } else {
                        toastr.error(result.extend.error);
                    }
                }
            });
        }
    }

    //分页显示回答mainarea
    function buildPage_answer_mainArea(result) {
        $("#answerArea").empty();

        //获取当前登录用户id
        var userId = $("#defaultDiv").attr("data-userId");
        //获取当前问题的提问用户id
        var questionUserId = $("#questionArea").attr("data-questionUserId");
        $.each(result.extend.pageInfo.list, function (index, item) {
            //去掉重复
            var answerId = item.id;
            if (answerId != $("#targetAnswer").attr("data-answerId")) {
                var fromuserid = item.user.id;
                var fromusername = item.user.nickname;
                //获取该回答的作者用户id和nickname
                var $div_out = $("<div data-answerId='" + item.id + "' class='my-2 p-3 rounded shadow-sm bg-white' style='position:relative;'>");
                //判断是否是置顶回答，添加上相应的图标
                if (item.top === true) {
                    //置顶图标
                    $div_out.append($("<div style='position:absolute;top:0;right:0'><img src='/images/setTop_right.svg' width='50px' height='50px'></div>"));
                }
                var $div_in_1 = $("<div class='border-bottom border-dark pb-1'>").append($("<div>").append($("<img src='" + item.user.headimgurl + "' width='40px' height='40px' class='rounded-circle'>")).append($("<a class='text-dark font-weight-bold' href='${APP_PATH}/user/"+item.user.id+"'>" + item.user.nickname + "</a>"))).append($("<div style='font-size:small'>" + item.user.slogan + "</div>"));
                var $div_in_2 = $("<div class='previewAnswerArea p-2'><p>" + item.answercontent + "</p></div>");
                var $div_in_3 = $("<div class='border-bottom border-gray pb-1' style='position:relative;'><span><i class='fa fa-arrow-circle-up text-success'></i>" + item.upvotenum + "</span><span class='ml-3'><i class='fa fa-arrow-circle-down text-danger'></i>" + item.downvotenum + "</span><span class='ml-3 small'>编辑于：" + new Date(item.edittime).toLocaleDateString() + "</span><div style='position: absolute;bottom:3px;right:3px;'><a class='btn btn-sm btn-outline-secondary' data-flag='true' data-answerId='" + item.id + "' onclick='optionClick(this)'><i class='fa fa-angle-double-down'></i>选项</a><a data-answerId='" + item.id + "' data-fromuserid='" + fromuserid + "' data-fromusername='" + fromusername + "' onclick='addComment(this)' class='ml-2 btn btn-sm btn-outline-secondary'><i class='fa fa-comments'></i>评论</a></div></div>");
                var $div_option_area;
                if (questionUserId === userId) {
                    //当前登录用户是问题的提问者，添加按钮，"回答置顶/取消置顶"和"删除回答"
                    if (item.top === true) {
                        //取消置顶，删除回答
                        $div_option_area = $("<div data-option-answerId='" + item.id + "' style='display: none;'><div class='d-flex p-2'><div class='flex-fill text-center'><a data-answerId='" + item.id + "' href='javascript:void(0);' onclick='agreeAnswer(this)' class='text-dark'><i class='fa fa-arrow-circle-up text-success'></i>赞同回答</a></div><div class='flex-fill text-center'><a data-answerId='" + item.id + "' onclick='disagreeAnswer(this)' href='javascript:void(0);' class='text-dark'><i class='fa fa-arrow-circle-down text-danger'></i>反对回答</a></div><div class='flex-fill text-center'><a data-answerId='" + item.id + "' onclick='viewComment(this)' href='javascript:void(0);' class='text-dark'><i class='fa fa-comments'></i>查看评论</a></div><div class='flex-fill text-center'><a data-answerId='" + item.id + "' onclick='reportAnswer(this)' href='javascript:void(0);' class='text-dark'><i class='fa fa-arrow-circle-right'></i>举报回答</a></div><div class='flex-fill text-center'><a data-answerId='" + item.id + "' onclick='cancelSetTopAnswer(this)' href='javascript:void(0);' class='text-dark'><i class='fa fa-arrow-circle-down text-secondary'></i>取消置顶</a></div><div class='flex-fill text-center'><a data-answerId='" + item.id + "' onclick='deleteAnswer(this)' href='javascript:void(0);' class='text-dark'><i class='fa fa-trash-alt text-danger'></i>删除回答</a></div></div></div>");
                    } else {
                        //回答置顶，删除回答
                        $div_option_area = $("<div data-option-answerId='" + item.id + "' style='display: none;'><div class='d-flex p-2'><div class='flex-fill text-center'><a data-answerId='" + item.id + "' href='javascript:void(0);' onclick='agreeAnswer(this)' class='text-dark'><i class='fa fa-arrow-circle-up text-success'></i>赞同回答</a></div><div class='flex-fill text-center'><a data-answerId='" + item.id + "' onclick='disagreeAnswer(this)' href='javascript:void(0);' class='text-dark'><i class='fa fa-arrow-circle-down text-danger'></i>反对回答</a></div><div class='flex-fill text-center'><a data-answerId='" + item.id + "' onclick='viewComment(this)' href='javascript:void(0);' class='text-dark'><i class='fa fa-comments'></i>查看评论</a></div><div class='flex-fill text-center'><a data-answerId='" + item.id + "' onclick='reportAnswer(this)' href='javascript:void(0);' class='text-dark'><i class='fa fa-arrow-circle-right'></i>举报回答</a></div><div class='flex-fill text-center'><a data-answerId='" + item.id + "' onclick='setTopAnswer(this)' href='javascript:void(0);' class='text-dark'><i class='fa fa-arrow-circle-up text-info'></i>回答置顶</a></div><div class='flex-fill text-center'><a data-answerId='" + item.id + "' onclick='deleteAnswer(this)' href='javascript:void(0);' class='text-dark'><i class='fa fa-trash-alt text-danger'></i>删除回答</a></div></div></div>");
                    }
                } else {
                    //普通用户，不能给问题置顶，或者删除回答
                    $div_option_area = $("<div data-option-answerId='" + item.id + "' style='display: none;'><div class='d-flex p-2'><div class='flex-fill text-center'><a data-answerId='" + item.id + "' href='javascript:void(0);' onclick='agreeAnswer(this)' class='text-dark'><i class='fa fa-arrow-circle-up text-success'></i>赞同回答</a></div><div class='flex-fill text-center'><a data-answerId='" + item.id + "' onclick='disagreeAnswer(this)' href='javascript:void(0);' class='text-dark'><i class='fa fa-arrow-circle-down text-danger'></i>反对回答</a></div><div class='flex-fill text-center'><a data-answerId='" + item.id + "' onclick='viewComment(this)' href='javascript:void(0);' class='text-dark'><i class='fa fa-comments'></i>查看评论</a></div><div class='flex-fill text-center'><a data-answerId='" + item.id + "' onclick='reportAnswer(this)' href='javascript:void(0);' class='text-dark'><i class='fa fa-arrow-circle-right'></i>举报回答</a></div></div></div>");
                }
                //评论区域
                var $commentArea = $("<div class='bg-light border-top border-dark' data-answer-comment-area-answerId='" + item.id + "'><div data-answer-comment-answerId='" + item.id + "'></div><div data-answer-comment-pagenav-answerId='" + item.id + "'></div></div>");
                $div_out.append($div_in_1).append($div_in_2).append($div_in_3).append($div_option_area).append($commentArea).appendTo($("#answerArea"));
            }
        });
    }

    //分页显示回答pagenav
    function buildPage_answer_pageNav(result) {
        var pageNavArea = $("#pageNavArea");
        pageNavArea.empty();

        var div = $("<div class='p-2'>");
        var ul = $("<ul></ul>").addClass("pagination");
        //遍历给ul中添加页码提示
        $.each(result.extend.pageInfo.navigatepageNums, function (index, item) {

            var numLi = $("<li class='page-item'></li>").append($("<a class='btn btn-sm btn-outline-primary mr-2'></a>").append(item));
            if (result.extend.pageInfo.pageNum === item) {
                //当前页按钮，不可点击
                numLi.find("a").removeClass("btn-outline-primary");
                numLi.find("a").addClass("disabled");
                numLi.find("a").addClass("btn-primary");
            }
            numLi.click(function () {
                to_page_answer(item);
            });
            ul.append(numLi);
        });
        div.append(ul).appendTo(pageNavArea);
    }

    //分页显示回答topage
    function to_page_answer(pn) {
        var questionId = $("#questionArea").attr("data-questionid");
        $.ajax({
            url: '/question/' + questionId + '/answers/' + pn,
            type: 'GET',
            success: function (result) {
                if (result.extend.pageInfo.list.length > 0) {
                    buildPage_answer_mainArea(result);
                    buildPage_answer_pageNav(result);
                } else {
                    $("<div class='alert-warning p-3'>该问题暂无回答，你可以添加回答，或者邀请其他用户回答。</div>").appendTo($("#mainArea"));
                }
            }
        });
    }

    function inviteUser(ele) {
        if (!hasLogin()) {
            toastr.error("请先登录！");
            return false;
        }
        var userId = $(ele).attr("data-userId");
        var questionId = $("#questionArea").attr("data-questionid");
        $.ajax({
            url: '/inviteUser/' + questionId + "/" + userId,
            type: 'GET',
            success: function (result) {
                if (result.code === 100) {
                    toastr.success("邀请成功！");
                    //删除该div
                    $("div[data-inviteUserId=" + userId + "]").remove();
                } else {
                    toastr.error("邀请失败，请稍后重试！");
                }
            }
        });
    }

    function buildPageNav_invite(result) {
        //清空
        $("#invitePageNavArea").empty();
        var div = $("<div class='p-2'>");
        var ul = $("<ul></ul>").addClass("pagination");
        //遍历给ul中添加页码提示
        $.each(result.extend.pageInfo.navigatepageNums, function (index, item) {

            var numLi = $("<li class='page-item'></li>").append($("<a class='btn btn-sm btn-outline-primary mr-2'></a>").append(item));
            if (result.extend.pageInfo.pageNum === item) {
                //当前页按钮，不可点击
                numLi.find("a").removeClass("btn-outline-primary");
                numLi.find("a").addClass("disabled");
                numLi.find("a").addClass("btn-primary");
            }
            numLi.click(function () {
                toPage_invite(item);
            });
            ul.append(numLi);
        });
        div.append(ul).appendTo($("#invitePageNavArea"));
    }

    //邀请用户回答div 的用户列表
    function buildMainPage_invite(result) {
        //清空
        $("#inviteBodyArea").empty();

        $("<h6 class='border-bottom border-gray pb-2 mb-0'>邀请用户</h6>").appendTo($("#inviteBodyArea"));
        $.each(result.extend.pageInfo.list, function (index, item) {
            var $div = $("<div data-inviteUserId='" + item.id + "' class='media text-muted pt-3' style='position:relative;'></div>")
            //邀请按钮
            var $button_invite = $("<a data-userId='" + item.id + "' onclick='inviteUser(this)' class='btn btn-sm btn-outline-info' style='position:absolute;top:4px;right:2px;'>邀请回答</a>");
            var $img = $("<img alt='头像' class='mr-2 rounded' style='width:32px;height:32px;' src='" + item.headimgurl + "'></img>");
            var $p = $("<p class='media-body pb-3 mb-0 small lh-125 border-bottom border-gray'><strong class='d-block text-gray-dark'>" + item.nickname + "</strong>" + item.slogan + "</p>");
            $div.append($button_invite).append($img).append($p).appendTo($("#inviteBodyArea"));
        });
    }

    //邀请用户回答div
    function toPage_invite(pn) {
        //查询用户关注的人
        var userId = $("#defaultDiv").attr("data-userId");
        if (userId.length != 16) {
            return false;
        }
        $.ajax({
            url: '/followingUser/' + userId + "/" + pn,
            type: 'GET',
            success: function (result) {
                if (result.code === 100) {
                    if (result.extend.pageInfo.list.length > 0) {
                        buildMainPage_invite(result);
                        buildPageNav_invite(result);
                    } else {
                        $("<div class='alert-warning p-3'><h3>你还没有关注任何用户，无法发送邀请。</h3><div>").appendTo($("#inviteArea"));
                    }
                }
            }
        });
    }

    //点击图片上传功能
    function alertImageUploadDiv() {
        $("#imageUploadDiv").show();
    }

    //点击显示问题详情按钮
    $("#btn-question-content").click(function () {
        var show = $("#btn-question-content").attr("data-show");
        if (show === 'false') {
            $("#btn-question-content").attr("data-show", "true");
            $("#btn-question-content").text("收起");
            $("#questionContentArea").show();
        } else {
            $("#btn-question-content").attr("data-show", "false");
            $("#btn-question-content").text("显示问题详情");
            $("#questionContentArea").hide();
        }
    });

    //点击添加回答
    $("#btn-answer-add").click(function () {
        if (!hasLogin()) {
            toastr.error("请先登录！");
            return false;
        }
        $("#answerAddArea").show();
    });

    //点击取消添加回答
    $("#btn-answer-add-cancel").click(function () {
        $("#answerAddArea").hide();
    });

    //点击提交添加回答按钮
    $("#btn-answer-submit").click(function () {
        var userId = $("#defaultDiv").attr("data-userId");
        if (userId.length != 16) {
            window.location.href = '/login';
            return false;
        }
        var questionId = $("#questionArea").attr("data-questionId");
        //校验表单
        var $html_out = $("#html-output");
        var answercontent = $("#answercontent");
        var content = $html_out.text();
        if (content.length < 10) {
            toastr.error("请输入较为详细的内容");
            return false;
        }
        answercontent.val(content);
        //开始提交
        $.ajax({
            url: '/submitAnswer',
            data: $("#addAnswerForm").serialize(),
            type: 'POST',
            success: function (result) {
                if (result.code === 100) {
                    window.location.href = '/question/' + questionId + "/answer/" + result.extend.answerId;
                } else {
                    toastr.error("添加回答失败，请稍后重试！");
                }
            }
        });
    });

    //点击邀请用户回答
    $("#btn-answer-invite").click(function () {
        if (!hasLogin()) {
            toastr.error("请先登录！");
            return false;
        }
        $("#inviteArea").show();
    });

    $("#btn-invite-hide-btn").click(function () {
        $("#inviteArea").hide();
    });

    //点击关注问题按钮
    $("#btn-question-star").click(function () {
        if (!hasLogin()) {
            toastr.error("请先登录！");
            return false;
        }
        var userId = $("#defaultDiv").attr("data-userId");
        var questionId = $("#questionArea").attr("data-questionId");
        $.ajax({
            url: '/addStarQuestion/' + userId + "/" + questionId,
            type: 'GET',
            success: function (result) {
                if (result.code === 100) {
                    toastr.success("关注问题成功！");
                } else {
                    toastr.error(result.extend.error);
                }
            }
        });
    });

    //点击举报问题按钮
    $("#btn-question-report").click(function () {
        if (!hasLogin()) {
            toastr.error("请先登录！");
            return false;
        }
        if (confirm("确认要举报该问题吗？请不要恶意举报")) {
            var questionId = $("#questionArea").attr("data-questionid");
            if (questionId.length == 16) {
                $.ajax({
                    url: '/report/question/' + questionId,
                    type: 'GET',
                    success: function (result) {
                        if (result.code === 100) {
                            toastr.success("操作成功！");
                        } else {
                            toastr.error(result.extend.error);
                        }
                    }
                });
            }
        }
    });

    $(function () {
        //获取邀请用户回答第一页的内容
        toPage_invite(1);
        to_page_answer(1);
        //pell容器初始化
        var editor = window.pell.init({
            element: document.getElementById('editor'),
            defaultParagraphSeparator: 'p',
            onChange: function (html) {
                document.getElementById('html-output').textContent = html
            }
        });

        //去掉拼写检查
        $(".pell-content").attr("spellcheck", "false");
        $(".pell-content").addClass("bg-white");

        //点击取消按钮
        $("#btn-cancel").click(function () {
            $("#imageUploadDiv").hide();
        });

        //图片上传
        var $gallery = $("#gallery"),
            $galleryImg = $("#galleryImg"),
            $uploaderInput = $("#uploaderInput"),
            $uploaderFiles = $("#uploaderFiles");
        var lil = "";

        //添加图片
        $uploaderInput.on("change", function (e) {
            var src;  //用于图片显示的地址
            var url = window.URL || window.webkitURL || window.mozURL;  //本地地址，用于图片显示的绝对地址
            var files = e.target.files;  //选取的图片文件
            var file = files[0];
            // 过滤掉非图片类型文件
            if (file.type.match('image.*')) {
                if (url) {
                    src = url.createObjectURL(file);
                } else {
                    src = e.target.result;
                }
                var tmpl = '';
                //动态创建li标签，用于显示符合的图片
                tmpl += '<li class="input-image-file"' + 'id="' + file.name + '" style="background-image:url(' + src + ')"></li>';
                $uploaderFiles.append(tmpl);
                ++lil;  //把创建的li标签加1，用于判断图片是否到达规定数目
            }
            if (lil >= 1) {
                //选中1张图片
                $('.input-image-box').css('display', 'none');
                $("#btn-submit").attr("data-flag", "true");
                $("#btn-submit").removeClass("disabled");
            } else {
                $('.input-image-box').css('display', 'block');
            }

        });


        var index;
        var tid;

        /*预览图片*/
        $uploaderFiles.on("click", "li", function () {
            index = $(this).index();
            tid = $(this).attr("id");
            $galleryImg.attr("style", this.getAttribute("style"));
            $gallery.fadeIn(100);
        });

        $gallery.on("click", function () {
            $gallery.fadeOut(100);
        });

        //删除图片
        $("#icon-delete").click(function () {
            $("#uploaderInput").val('');
            //删除该图片的节点
            $uploaderFiles.find("li").eq(index).remove();
            --lil;   //存储li标签的个数减1
            //做判断，如果图片到达9张

            $('.input-image-box').css('display', 'block');
            //修改保存按钮属性
            $("#btn-submit").attr("data-flag", "false");
            $("#btn-submit").addClass("disabled");
        });

        //上传图片
        $("#btn-submit").click(function () {
            //上传图片
            if ($("#btn-submit").attr('data-flag') === "true") {
                //js获取图片对象
                var formFile = new FormData();
                formFile.append("files", document.getElementById("uploaderInput").files[0]);
                $.ajax({
                    url: "/filesUpload",
                    data: formFile,
                    type: "POST",
                    dataType: "json",
                    cache: false,//上传文件无需缓存
                    processData: false,//用于对data参数进行序列化处理 这里必须false
                    contentType: false, //必须
                    success: function (result) {
                        //接收返回的图片路径
                        if (result.code === 100) {
                            //图片上传成功，result.extend.fileList.index0
                            //1.去掉输入框中的文件缓存
                            $("#uploaderInput").val('');
                            //删除该图片的节点
                            $uploaderFiles.find("li").remove();
                            $('.input-image-box').css('display', 'block');
                            //修改按钮属性
                            $("#btn-submit").attr("data-flag", "false");
                            $("#btn-submit").addClass("disabled");
                            //2.将图片插入div中
                            var url = result.extend.fileList.index0;
                            //光标返回到原来编辑的位置
                            $("div[contenteditable='true']").focus();
                            //开始插入图片
                            document.execCommand('InsertImage', false, url);
                            //3.隐藏上传图片框
                            $("#imageUploadDiv").hide();
                            toastr.success("图片上传成功！");
                        } else {
                            toastr.success("图片上传失败，请重试！！！");
                        }
                    }
                })
            } else {
                toastr.error("请先选择图片");
            }
        });
    });
    $("#questionArea img").click(function () {
        $("#galleryImg2").attr("style", "background-image:url('" + $(this).attr("src") + "')");
        $("#gallery2").fadeIn(100);
    });

    $("#gallery2").click(function () {
        $("#gallery2").fadeOut(100);
    });
</script>
</body>
</html>
